package com.ll.app.controller.jj;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiUserGetRequest;
import com.dingtalk.api.response.OapiUserGetResponse;
import com.ll.app.api.jj.JJUserDTO;
import com.ll.app.api.jj.enums.JJRoleEnum;
import com.ll.app.api.req.WechatUserLoginDTO;
import com.ll.app.api.req.WechatUserRegisterReqDTO;
import com.ll.base.dto.ApiResultDTO;
import com.ll.base.dto.PageReqDTO;
import com.ll.base.dto.TenantAndIdDTO;
import com.ll.base.util.ListUtil;
import com.ll.domain.dingtalk.base.DingTalkUserBaseService;
import com.ll.domain.dingtalk.constant.URLConstant;
import com.ll.domain.dingtalk.utils.AccessTokenUtil;
import com.ll.domain.user.biz.UserDomainService;
import com.ll.domain.user.dto.UserDTO;
import com.taobao.api.ApiException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/jj/user")
@RequiredArgsConstructor
@Api(tags = "基金用户相关API")
public class JJUserController {

    private final DingTalkUserBaseService dingTalkUserBaseService;

    @ResponseBody
    @ApiOperation(value = "钉钉登陆")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ApiResultDTO login(@RequestParam(value = "authCode") String requestAuthCode) throws ApiException {
        String jjToken = AccessTokenUtil.getJJToken();
        String dUserId = dingTalkUserBaseService.login(jjToken, requestAuthCode);

        DingTalkClient client = new DefaultDingTalkClient(URLConstant.URL_USER_GET);
        OapiUserGetRequest request = new OapiUserGetRequest();
        request.setUserid(dUserId);
        request.setHttpMethod("GET");
        OapiUserGetResponse response = client.execute(request, jjToken);
        log.info(" getByUserId -> {} ", JSONObject.toJSONString(response));

        List<JJRoleEnum> jjRoleEnums = ListUtil.fitlerAndToList(response.getRoles()
                , r -> JJRoleEnum.checkRoleName(r.getName()), k -> JJRoleEnum.valueOf(k.getName()));

        JJRoleEnum maxRole = JJRoleEnum.getMaxRole(jjRoleEnums);
        JJUserDTO userDTO = JJUserDTO.builder()
                .dingUid(response.getUserid())
                .name(response.getName())
                .role(maxRole)
                .roleIndex(maxRole.ordinal())
                .build();
        return ApiResultDTO.success(userDTO);
    }


}


